package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;

import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

/**
 * 根据条件进行匹配查询
 * @author tangdelong
 * 2015年12月11日
 */
public class ListElementGenerator extends AbstractXmlElementGenerator {
	
	public ListElementGenerator(){
		super();
	}
	
	@Override
	public void addElements(XmlElement parentElement) {
		XmlElement answer = new XmlElement("select"); //$NON-NLS-1$

        answer.addAttribute(new Attribute(
                "id", introspectedTable.getListStatementId())); //$NON-NLS-1$
        
        FullyQualifiedJavaType parameterType = introspectedTable.getRules()
                .calculateAllFieldsClass();
        
        answer.addAttribute(new Attribute("resultType", //$NON-NLS-1$
        		parameterType.getShortName()));

        answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$
        		parameterType.getShortName()));

        context.getCommentGenerator().addComment(answer);
        

        StringBuilder sb = new StringBuilder();
        sb.append("select "); //$NON-NLS-1$

        if (stringHasValue(introspectedTable
                .getSelectByPrimaryKeyQueryId())) {
            sb.append('\'');
            sb.append(introspectedTable.getSelectByPrimaryKeyQueryId());
            sb.append("' as QUERYID,"); //$NON-NLS-1$
        }
        answer.addElement(new TextElement(sb.toString()));
        answer.addElement(getColumn3ListElement());

        sb.setLength(0);
        sb.append("from "); //$NON-NLS-1$
        sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
        answer.addElement(new TextElement(sb.toString()));
        sb.setLength(0);
        XmlElement insertNotNullElement = new XmlElement("where");
        insertNotNullElement.addElement(new TextElement("<include refid=\"equal\" />"));
        
        answer.addElement(insertNotNullElement);

        if (context.getPlugins()
                .sqlMapSelectByPrimaryKeyElementGenerated(answer,
                        introspectedTable)) {
            parentElement.addElement(answer);
        }
		
	}
}
